/*
 * Copyright (C) 2010 Seapeak.Xu
 *
 * fostmq may be copied only under the terms of the GNU General
 * Public License V3, which may be found in the fostmq source kit.
 *
 * Created on: 2010-7-28
 * Author: Seapeak.Xu
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "fost_string.h"

char *ltrim(char *value)
{
	char *ptmp;
	char *end;
	int length;

	end = value + strlen(value);
	for (ptmp = value; ptmp < end; ptmp++)
	{
		if (!(' ' == *ptmp || '\n' == *ptmp || '\r' == *ptmp || '\t' == *ptmp))
		{
			break;
		}
	}

	if (ptmp == value)
	{
		return value;
	}

	length = (end - ptmp) + 1; //including \0
	memmove(value, ptmp, length);
	return value;
}

char *rtrim(char *value)
{
	int length;
	char *ptmp;
	char *end;

	length = strlen(value);
	if (length == 0)
	{
		return value;
	}

	end = value + length - 1;
	for (ptmp = end; ptmp >= value; ptmp--)
	{
		if (!(' ' == *ptmp || '\n' == *ptmp || '\r' == *ptmp || '\t' == *ptmp))
		{
			break;
		}
	}

	if (ptmp != end)
	{
		*(ptmp + 1) = '\0';
	}

	return value;
}

char *trim(char *value)
{
	ltrim(value);
	rtrim(value);
	return value;
}

char *bin2hex(const char *bin_buff, const int len, char *buff)
{
	unsigned char *ptr;
	unsigned char *end;
	int index;

	index = 0;
	end = (unsigned char *) bin_buff + len;
	for (ptr = (unsigned char *) bin_buff; ptr < end; ptr++)
	{
		index += sprintf(buff + index, "%02x", *ptr);
	}

	buff[index] = '\0';
	return buff;
}
